package com.coship.vas.dapg.mule;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.mule.api.MuleContext;
import org.mule.config.builders.MuleXmlBuilderContextListener;

import com.coship.vas.dapg.util.ProcessAmBeanMap;

/**
 * 获取MULE上下文
 * @作者 905613 陈开源 深圳市同洲电子股份有限公司(增值运营产品线)
 *
 */
public class DAPGMuleListener extends MuleXmlBuilderContextListener {
        
    private Logger logger = Logger.getLogger(DAPGMuleListener.class);

	/**
	 * Mule 上下文
	 */
    private MuleContext muleContext;

    /**
     * @see ServletContextListener#contextInitialized(ServletContextEvent)
     */
    public void contextInitialized(ServletContextEvent event) {
        initMule(event.getServletContext());
        logger.info("process am service :"+ProcessAmBeanMap.getInstance().getService(System.getProperty("system.current.media.name")+"-"+System.getProperty("system.current.media.version")));
    }

    /**
     * 上下文销毁
     */
    public void contextDestroyed(ServletContextEvent arg0) {
        // TODO Auto-generated method stub
    }
   
    /**
     * 初始化上下文
     * @param context
     */
    private void initMule(ServletContext context) {
        String config = context.getInitParameter("org.mule.config");
        if (config == null) {
            config = getDefaultConfigResource();
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("No Mule config file(s) specified, using default: " + config);
            }

        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug("Mule config file(s): " + config);
        }
        try {
            this.muleContext = super.createMuleContext(config, context);
            this.muleContext.start();
            // 设置muleContext
            MuleContextSession.getInstance().setMuleContext(this.muleContext);
            logger.info("mule start success!");
        } catch (Exception e) {
            logger.error(e);
        }
    }
}
